package com.apes.fn.tms.service;

import com.alibaba.fastjson.JSONObject;
import com.apes.fn.tms.model.Site;
import com.apes.fn.tms.model.Site;
import com.apes.fn.tms.repository.SiteRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.stock.model.Location;
import com.apestech.framework.json.JSON;
import com.apestech.framework.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service("siteService")
public class SiteService extends DomainService {
    @Autowired
    SiteRepository siteRepository;

    public Site create(SimpleRequest simpleRequest){
        Site site = simpleRequest.getO(Site.class);
        return siteRepository.saveAndFlush(site);
    }

    public Site update(SimpleRequest simpleRequest){
        Site site = simpleRequest.getO(Site.class);
        return siteRepository.saveAndFlush(site);
    }

    private String delete(SimpleRequest simpleRequest){
        Integer versions = simpleRequest.get("version");
        Site site = simpleRequest.getO(Site.class);
        if (site.getVersion() != versions) throw new RuntimeException("记录已更新或已删除，请重新提交！");
        siteRepository.delete(site);
        return "删除成功";
    }


    /**
     * 功能：下拉模糊查询使用
     * @param request
     * @return
     */
    public Page<Site> find(SimpleRequest request) {
        Map map = request.getMap();
        if (!map.containsKey("key")){
            return siteRepository.findAll(PageRequest.of(request.get("page"), request.get("size")) );
        }
        String value = request.get("key");
        return siteRepository.find(value, value, PageRequest.of(request.get("page"), request.get("size")) );
    }
	
	/**
     * 老框架根据仓库找到对应的站点信息
     * @param request
     * @return
     */
    public Site oldQrySite(SimpleRequest request) {
        List<String> condiCKKQ = new ArrayList<>();
        JSONObject.parseArray(request.get("CKKQID").toString()).forEach(singleCKKQ -> {
            condiCKKQ.add(((JSONObject) singleCKKQ).getString("CKKQID"));
        });
        return siteRepository.oldQrySite(condiCKKQ);
    }

    public Map oldPhyDepotAddress(SimpleRequest request) {
        return siteRepository.oldPhyDepotAddress(request.get("site_id"));
    }
}
